#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STR_LEN 255

int countAnagrams(const char *, const char *); /* 统计变位词个数 */
int areAnagrams(const char *, const char *); /* 变位词判断 */

/* 辅助函数 */
int read_line(char *, int); /* 读入不超过指定长度的字符串 */
void lowcase(char *); /* 将字符串变为小写 */

int main()
{
    char text[STR_LEN + 1] = {'\0'};
    char word[STR_LEN + 1] = {'\0'};
    int cnt = 0;

    read_line(text, STR_LEN);
    read_line(word, STR_LEN);

    cnt = countAnagrams(text, word);

    printf("The text is \"%s\".\n", text);
    printf("The word is \"%s\".\n", word);
    printf("The count of anagrams is %d.\n", cnt);

    return 0;
}

/* 函数实现 */
/* 读入一行不超过指定长度的字符串 */
int read_line(char *str, int n)
{
    int ch, i = 0;

    /* 读入字符，直到遇到换行符 */
    while ((ch = getchar()) != '\n' && ch != '\r' && ch!=EOF)
    {
        if(i < n) /* 最大字符数 */ 
        { str[i++] = ch; }
     }
     str[i] = '\0'; /* 添加空字符'\0' */ 
     return i; /* 返回读入的字符数 */ 
}



void lowcase(char *s)
{
         int i=0;
	while(s[i]!='\0')
	{
		if(s[i]>='A'&&s[i]<='Z')
		{
			s[i]+=32;
		}
		i++;
	}
}
int compare(const void *q,const void *p)
{
return *((const char*)q)-*((const char*)p);
}
int areAnagrams(const char *word1,const char *word2)
{
	int size,nu=0;
	size=strlen(word2);
	char *temp1=NULL,*temp2=NULL;
	temp1=(char *)malloc((size+1)*sizeof(char));
	temp2=(char *)malloc((size+1)*sizeof(char));
	if(temp1==NULL||temp2==NULL)
	{
		exit(1);
	}
	strcpy(temp1,word1);
	strcpy(temp2,word2);
	lowcase(temp1);
	lowcase(temp2);
	qsort(temp1,size,sizeof(char),compare);
	qsort(temp2,size,sizeof(char),compare);
        nu=strncmp(temp1,temp2,size);
	if(nu==0)
	{
		return 1;
	}
	else
	{
		return 0;
	}
	free(temp1);
        temp1==NULL;
	free(temp2);
        temp2==NULL;			

}
int countAnagrams(const char *text, const char *word)
{
	int sign=0,i=0,count=0;
	int size,j=0;
	size=strlen(word);
	char *let=NULL;
	let=(char *)malloc((size+1)*sizeof(char));
	if(let==NULL)
	{
		exit(1);
	}
	while(*(text+j)!='\0')
	{

		strncpy(let,(text+j),size);
		let[size+1]='\0';
		sign=areAnagrams(let,word);
		if(sign==1)
		{
			count++;
			j+=size;
		}
		else
		{
			j++;
		}

	}
	free(let);
	return count;
}

